package com.itheima.common;

import com.itheima.exception.CustomException;
import com.itheima.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Objects;

/**
 * @Author: 斌
 * @DateTime: 2023年02月06日  14:26:47
 * @Description: com.itheima.common
 * @Version: 1.0
 */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    /*@ExceptionHandler(RuntimeException.class)
    public R  Exception(RuntimeException exception){
        log.error("异常信息4:{}", (Object) exception.getStackTrace());
        return R.error("网络异常，请稍后重试" );
    }*/


    // 数据库的约束错误信息，可能有很多：主键 唯一 非空约束 外键约束
    @ExceptionHandler(DataAccessException.class)
    public R  handlerSQLConstraintException(DataAccessException exception){
        log.error("异常信息1:{}",exception.getMessage());
        if (Objects.requireNonNull(exception.getMessage()).contains("Duplicate entry")){
            //数据库的约束错误信息
            String msg = exception.getMessage().split(" ")[9];
           return R.error(msg + "已存在");
        }
        return R.error("数据异常！！");
    }

    /**
     * 类型转换异常
     * @param exception
     * @return
     */
    @ExceptionHandler(ClassCastException.class)
    public R  ClassCastException(ClassCastException exception){
        log.error("异常信息2:{}",exception.getMessage());
            return R.error("添加失败,请重试" );
    }

    /**
     * 自定义业务异常
     * @param exception
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R  Exception(CustomException exception){
        log.error("异常信息3:{}",exception.getMessage());
        return R.error(exception.getMessage() );
    }

    /**
     * 其它未知异常
     * @param exception
     * @return
     */



}
